<template>
  <div>
    <div
      class=""
      style="display: flex;flex-direction: row;justify-content: space-between;"
    >
      <!--左侧公司树图-->
      <div class="leftContent">
        <el-input
          style="margin-bottom: 10px"
          size="mini"
          placeholder="请输入分公司名称"
          v-model="filterText"
        >
        </el-input>
        <el-tree
          class="filter-tree"
          :data="treeData"
          :props="defaultProps"
          default-expand-all
          :filter-node-method="filterNode"
          @node-click="nodeClick"
          ref="tree"
        >
        </el-tree>
      </div>
      <!--右侧内容-->
      <div style="width: 85%;height: 500px;background: white;overflow: auto">
        <div class="filter-container" style="padding: 10px 20px">
          <!--右侧顶部查询条件-->
          <div style="margin-top: 15px">
            <el-form
              :inline="true"
              :model="listQuery"
              size="mini"
              label-width="auto"
            >
              <el-form-item prop="keyword" label="账号：">
                <el-input
                  placeholder="请输入用户账号"
                  v-model="listQuery.username"
                ></el-input>
              </el-form-item>
              <el-form-item prop="nickName" label="姓名：">
                <el-input
                  placeholder="请输入用户姓名"
                  v-model="listQuery.nickName"
                ></el-input>
              </el-form-item>
              <el-form-item prop="phoneNumber" label="手机号：">
                <el-input
                  placeholder="请输入手机号"
                  v-model="listQuery.phoneNumber"
                ></el-input>
              </el-form-item>
              <el-form-item prop="status" label="状态：">
                <el-select
                  v-model="listQuery.status"
                  placeholder="请选择用户状态"
                >
                  <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button
                  style="float: right"
                  type="primary"
                  icon="el-icon-search"
                  @click="handleSearchList()"
                  size="small"
                  v-debounce="1500"
                  >查询</el-button
                >
                <el-button
                  style="float: right; margin-right: 15px"
                  icon="el-icon-refresh"
                  @click="handleResetSearch()"
                  size="small"
                  >重置</el-button
                >
              </el-form-item>
            </el-form>
          </div>
          <!---->

          <!--查询列表-->
          <div class="table-container">
            <el-table
              ref="tableDataRef"
              :data="list"
              height="400"
              style="width: 100%"
              v-loading="listLoading"
              size="mini"
              @selection-change="selectTableList"
              border
            >
              <el-table-column type="selection" width="40"></el-table-column>
              <el-table-column
                label="编号"
                width="100"
                align="center"
                type="index"
              ></el-table-column>
              <el-table-column
                label="帐号"
                align="center"
                prop="username"
              ></el-table-column>
              <el-table-column
                label="姓名"
                align="center"
                prop="nickName"
              ></el-table-column>
              <el-table-column
                label="所属分公司"
                align="center"
                prop="deptName"
              ></el-table-column>
              <el-table-column
                label="手机号"
                align="center"
                prop="phoneNumber"
              ></el-table-column>
              <!--<el-table-column label="邮箱" align="center" prop="email"></el-table-column>-->
              <el-table-column
                label="添加时间"
                width="160"
                align="center"
                prop="createTime"
              ></el-table-column>

              <el-table-column label="是否启用" width="140" align="center">
                <template slot-scope="scope">
                  <el-tag
                    size="mini"
                    :type="scope.row.status === 1 ? 'success' : 'danger'"
                    >{{ scope.row.status === 1 ? "启用" : "禁用" }}</el-tag
                  >
                </template>
              </el-table-column>
            </el-table>
          </div>
          <!--分页-->
          <div class="pagination-container" style="padding-bottom: 20px">
            <el-pagination
              background
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              layout="total, sizes,prev, pager, next,jumper"
              :current-page.sync="listQuery.pageNum"
              :page-size="listQuery.pageSize"
              :page-sizes="[5, 10, 15, 20]"
              :total="total"
            >
            </el-pagination>
          </div>
        </div>
      </div>
    </div>
    <div class="select-btn">
      <el-button size="small" type="primary" @click="ok">确认选择</el-button>
    </div>
  </div>
</template>
<script>
import { mapGetters } from "vuex";
import { fetchList, updateStatus } from "@/api/login";
import { formatDate } from "@/utils/date";
import { treeList } from "@/api/treeList";
import { authPhone } from "@/utils/auth.js";
const defaultListQuery = {
  pageNum: 1,
  pageSize: 10,
  username: null,
  nickName: "",
  phoneNumber: "",
  status: ""
};
const defaultAdmin = {
  id: null,
  username: null,
  password: null,
  nickName: null,
  email: null,
  note: null,
  status: 1,
  phoneNumber: null
};
export default {
  name: "adminList",
  computed: {
    ...mapGetters(["sidebar", "avatar", "name"])
  },
  props: {
    handleNum: {
      type: String,
      default: ""
    },
    checked: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      listQuery: Object.assign({}, defaultListQuery), //查询条件
      list: null, //查询列表数据
      total: null,
      listLoading: false, //查询数据列表加载loading状态
      dialogVisible: false, //添加用户弹框显示
      admin: Object.assign({}, defaultAdmin),
      isEdit: false, //编辑状态
      allocDialogVisible: false, //分配角色弹框
      allocRoleIds: [], //选择的角色数据
      allRoleList: [], //角色列表
      allocAdminId: null,
      filterText: "", //左侧筛选数据
      treeData: [], //左侧树图数据
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 搜索条件状态下拉数据
      options: [
        { value: "1", label: "启用" },
        { value: "0", label: "停用" }
      ],
      // 批量删除
      deleteList: [],
      // 部门树选项
      deptOptions: [],
      checkBox: []
    };
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.getList();

    this.getTreeData();
  },
  filters: {
    formatDateTime(time) {
      if (time == null || time === "") {
        return "N/A";
      }
      let date = new Date(time);
      return formatDate(date, "yyyy-MM-dd hh:mm:ss");
    }
  },
  methods: {
    ok() {
      if (this.handleNum == "one" && this.checkBox.length > 1) {
        return this.$message.warning("只能选择一个用户");
      } else {
        // const selectProduct = this.checkBox.map(item => {
        //   return {
        //     id: item.id,
        //     pic: item.pic,
        //     name: item.name
        //   };
        // });
        this.$emit("getStoreItem", this.checkBox);
      }
      // this.$emit("getStoreItem", this.checkBox);
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 点击左侧公司树图
    nodeClick(data, node, self) {
      this.listLoading = true;
      this.listQuery.deptId = data.id;
      fetchList(this.listQuery).then(response => {
        this.listLoading = false;
        this.list = response.data.list;
        this.total = response.data.total;
      });
    },
    // 获取公司树图数据
    getTreeData() {
      const params = {
        id: "",
        parentId: "",
        deptName: "",
        status: ""
      };
      treeList(params).then(res => {
        if (res.code === 200) {
          this.treeData = res.data;
        }
      });
    },
    // 重置查询条件
    handleResetSearch() {
      this.listQuery = Object.assign({}, defaultListQuery);
      this.getList();
    },
    // 查询列表
    handleSearchList() {
      this.listQuery.pageNum = 1;
      this.getList();
    },
    handleSizeChange(val) {
      this.listQuery.pageNum = 1;
      this.listQuery.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listQuery.pageNum = val;
      this.getList();
    },
    async handleAdd() {
      // await this.getAllRoleList();
      await this.$refs.addUserForm.getAffilcation();
      this.dialogVisible = true;
      this.isEdit = false;
      this.admin = Object.assign({}, defaultAdmin);
    },
    // 列表中是否启用开关
    handleStatusChange(index, row) {
      this.$confirm("是否要修改该状态?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          updateStatus(row.adminId, { status: row.status }).then(response => {
            this.$message({
              type: "success",
              message: "修改成功!"
            });
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消修改"
          });
          this.getList();
        });
    },

    // 获取用户列表数据
    getList() {
      if (
        this.listQuery.phoneNumber &&
        !authPhone(this.listQuery.phoneNumber)
      ) {
        return this.$message.error("请输入正确的手机号");
      }
      this.listLoading = true;
      fetchList(this.listQuery)
        .then(response => {
          this.listLoading = false;
          this.list = response.data.list;
          this.total = response.data.total;

          this.$nextTick(() => {
            this.toggleRowSelection();
          });
        })
        .finally(() => {
          this.listLoading = false;
        });
    },
    toggleRowSelection() {
      if (this.checked) {
        let checkedList = [];
        this.checked.forEach(v => {
          this.list.forEach(v1 => {
            if (v1.adminId === v) {
              checkedList.push(v1);
            }
          });
        });
        checkedList.forEach(v => {
          this.$refs.tableDataRef.toggleRowSelection(v, true);
        });
        this.selectList = checkedList;
      }
    },
    selectTableList(val) {
      this.checkBox = val;
    }
  }
};
</script>
<style scoped>
.leftContent {
  margin-right: 10px;
  width: 15%;
  height: 500px;
  overflow: auto;
  background: white;
  padding: 20px 10px;
}
.select-btn {
  text-align: right;
  margin-top: 10px;
}
// table表头固定
:deep(.el-table) {
  overflow: visible;
}

:deep(.el-table__header-wrapper) {
  position: sticky;
  top: 100px; //这个值根据实际情况而定
  z-index: 10;
}
</style>
